<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
class Test extends Base{

    public function index(){

        return $this->fetch();

    }
	
	public function qrcode(){
		$wxinfo = $this->getSignPackage();
		$this->assign('wxinfo',$wxinfo);
		return $this->fetch();
	}

    public function test(Request $request){
        // echo preg_match("/cli/i", php_sapi_name()) ? true : false;
        echo php_sapi_name();
        // while(true){
        //     $inserttime = $request->param('infodata');
        //     $data['insert_time'] = $inserttime.date('Y-m-d H:i:s',time());
        //     Db::name('test')->insert($data);
        //     sleep(15);
        //     continue;
        // }
    }

    public function saveimg(){
        return $this->fetch();
    }
    public function saveimg2(){
        return $this->fetch();
    }

    public function baseToimg(Request $request){
        $base64_image_content ="";
        // $base64_image_content = $_POST["img_value"];


        if($base64_image_content==''){echo '错误';exit;}
        
        $base64_image_content = htmlspecialchars($base64_image_content);
        
        $output_directory = 'public/static/image'; //设置图片存放路径
        /* 检查并创建图片存放目录 */
        if (!file_exists($output_directory)) {
            mkdir($output_directory, 0777);
            // mkdir($output_directory);
        }
        
        /***每一天创建一个文件夹**/
        /* 根据base64编码获取图片类型 */
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $image_type = $result[2]; //data:image/jpeg;base64,
            $output_file = $output_directory . '/' . md5(time()) . '.' . $image_type;
        }
        
        //echo $output_file;
        
        /* 将base64编码转换为图片编码写入文件 */
        $image_binary = base64_decode(str_replace($result[1], '', $base64_image_content));
        if (file_put_contents($output_file, $image_binary)) {
            $img_url = $output_file; //写入成功输出图片路径
            return "/".$output_file;
        }
        // if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        //     $type = $result[2];
        //     $new_file = "/public/static/uploads/".date('Ymd',time())."/";
        //     if(!file_exists($new_file)){
        //         //检查是否有该文件夹，如果没有就创建，并给予最高权限
        //         mkdir($new_file, 0700);
        //     }
        //     $new_file = $new_file.time().".{$type}";
        //     if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
        //         return $new_file;
        //     }else{
        //         return false;
        //     }
        // }else{
        //     return false;
        // }
    }

    public function download(){
        $header = array(
            'Accept: application/json',
         );
         $url = "https://h5vv.video.qq.com/getinfo?vid=m3128kamff9&otype=json&platform=4210801&callback=.";
         $curl = curl_init();
         //设置抓取的url
         curl_setopt($curl, CURLOPT_URL, $url);
         //设置头文件的信息作为数据流输出
         curl_setopt($curl, CURLOPT_HEADER, 0);
         // 超时设置,以秒为单位
         curl_setopt($curl, CURLOPT_TIMEOUT, 1);
      
         // 超时设置，以毫秒为单位
         // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
      
         // 设置请求头
         curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
         //设置获取的信息以文件流的形式返回，而不是直接输出。
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
         //执行命令
         $data = curl_exec($curl);
      
         // 显示错误信息
         if (curl_error($curl)) {
             print "Error: " . curl_error($curl);
         } else {
             // 打印返回的内容
             print_r(json_decode($data));
             print_r(json_decode($data,true));
            //  $this->assign(['data'=>$data]);
             curl_close($curl);
         }
        return $this->fetch();
    }

    public function phpinfos(){
        echo phpinfo();
    }

    public function getvideo(){
        $httpurl = "https://v.qq.com/x/cover/wc9ltjvvebbrfgo/g08494v2t0y.html";
        $str = explode('/',$httpurl);
        $count = count($str);
        $needstr = $str[$count-1];

        $result = explode('.',$needstr);
        $vid = $result[0];
        print_r($vid);
    }

    public function websocket(){
        return $this->fetch();
    }
	
	
	
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => 'wxc1945845b6c38dc1',
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );

        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }


    private function log($msg) {
        $log_file_path = dirname(__FILE__) . '/debug.log';
        error_log($msg.PHP_EOL, 3, $log_file_path);
    }
    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode($this->get_php_file("jsapi_ticket.php"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $this->log(print_r($res, true));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $this->set_php_file("jsapi_ticket.php", json_encode($data));
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }

        return $ticket;
    }

    private function getAccessToken() {
		$appid = "wxc1945845b6c38dc1";
		$appSecret = "d22bf7b191f8e7adebdcccd265600f56";
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode($this->get_php_file("access_token.php"));
        if ($data->expire_time < time()) {
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";
            $res = json_decode($this->httpGet($url));
            $this->log(print_r($res, true));
			print_r($res);
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $this->set_php_file("access_token.php", json_encode($data));
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    private function get_php_file($filename) {
        return trim(substr(file_get_contents($filename), 15));
    }
    private function set_php_file($filename, $content) {
        $fp = fopen($filename, "w");
        fwrite($fp, "<?php exit();?>" . $content);
        fclose($fp);
    }
	
	public function upload(Request $request){
		return $this->fetch();
	}
	
	// 手机摇一摇
	public function shakesway(){
		return $this->fetch();
	}
}